from util.sqlite_util import conn, cursor
from entity.student import Student
from util.log_util import LogUtil
import random

class StudentDao:

    # 插入或更新
    @staticmethod
    def insertOrUpdate(student :Student):
        try:
            if student.id <= 0 :
                id = random.randint(1000000000,10000000000)
                student.id = id
                cursor.execute('INSERT INTO student (id, name, age) VALUES (?, ?, ?)', (student.id, student.name, student.age))
                conn.commit()
            else :
                cursor.execute('UPDATE student SET name = ?, age = ? where id = ?', (student.name, student.age , student.id))
                conn.commit()
        except Exception as e:
            LogUtil.error(f'>>> StudentDao insertOrUpdate 发生错误!\n{e}')
        else:
            LogUtil.error('>>> student:id{id} 更新成功!!!'.format(id=student.id))
        finally:
            pass
    
    # 查询
    @staticmethod
    def query(name :str=None, age :str=None, id :int=None):
        sql = 'SELECT id,name,age FROM student where 1=1 '
        if name != None:
            sql += f" AND name LIKE '%%{name}%%' "
        if age != None:
            sql += f" AND age = {age} "
        if id != None:
            sql += f" AND id = {id} "
        
        try:
            cursor.execute(sql)
            result = [Student.fromDbRow(row[0], row[1], row[2]) for row in cursor.fetchall()]
            return result
        except Exception as e:
            LogUtil.error(f'>>> StudentDao query 发生错误!\n{e}')
            return None